package com.cloud_disk.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：李子璇
 * 日期：2021/12/23 13:31
 */
@Controller
@RequestMapping("/file")
public class FileController {
    @Value("${file.upload.path}")
    private  String filePath;

    @Value("${file.upload.relative}")
    private  String fileRelativePath;

    @RequestMapping("/uploadForm")
    public String uploadForm(){

        return "/PictureUpload";
    }



    @RequestMapping("/listFiles")
    public String listFiles(ModelMap map){
        File file=new File(filePath);

        String[] fileNames=file.list();

        List<String> files=new ArrayList<>();
        for(String fs:fileNames){
            files.add(fileRelativePath.replace("*","")+fs);
        }
        map.put("files",files);

        return "/PictureList";
    }

    @RequestMapping(value="/PictureUpload",method = RequestMethod.POST)
    public String upload(MultipartFile pictureFile, ModelMap map) throws IOException {

        //获取文件原名
        String pictureFileName=pictureFile.getOriginalFilename();

        //创建上传的文件对象
        File newfile=new File(filePath,pictureFileName);

        //将文件复制到对应地址
        pictureFile.transferTo(newfile);

        //map.put("imgPath",fileRelativePath.replace("*","")+pictureFileName);
        return "redirect:/file/listFiles";
    }

    @RequestMapping("/download")
   /* public void downLoad(String name, HttpServletResponse response){
        name=name.substring(name.lastIndexOf("/")+1);

        String newName=UUID.randomUUID().toString()+name;

        System.out.println(name);
        response.setContentType("application/octet-stream;charset=UTF-8");

        response.setHeader("Content-Disposition","attachment;filename"+name+"");

        try {

            FileInputStream fis=new FileInputStream(filePath+name);

            ServletOutputStream outputStream=response.getOutputStream();
            int len=0;
            byte[] buf=new byte[1024];
            while((len=fis.read(buf))!=-1){
                outputStream.write(buf,0,len);
            }
            fis.close();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/

    public void download(String name, HttpServletResponse resp, HttpSession session) throws Exception {
        name = name.substring(name.lastIndexOf("/")+1);
        System.out.println(name);
        // 下载时文件名会乱码或不显示，进行转码
        String downloadFielName = new String(name.getBytes("UTF-8"), "iso-8859-1");
        // 设置响应的内容类型为流的方式
        resp.setContentType("application/octet-stream");
        // 让服务器告诉浏览器它发送的数据属于什么文件类型（流）
        resp.setHeader("content-type", "application/octet-stream");
        // 告诉浏览器这个文件的类型和名字(attachment--以附件的方式)
        resp.setHeader("Content-Disposition", "attachment;filename=" + downloadFielName);

//        String realPath = session.getServletContext().getRealPath("images");
        String realPath = filePath;
        // 以流的方式将文件从真实的存储地址读回来--内存
        FileInputStream fis = new FileInputStream(realPath + File.separator + name);
        ServletOutputStream os = resp.getOutputStream();
        int len = 0;
        // 自定义缓冲区（缓冲区的大小为1024）
        byte[] b = new byte[1024];
        while ((len = fis.read(b)) != -1) {
            os.write(b, 0, len);
        }
        os.close();
        fis.close();
    }
}
